import taskService from "@/api/services/taskService";
import { PlusOutlined } from "@ant-design/icons";
import {
	Checkbox,
	DatePicker,
	Form,
	Input,
	InputNumber,
	Modal,
	Select,
	Space,
	Tabs,
	Upload,
} from "antd";
import { message } from "antd";
import type { RcFile, UploadProps } from "antd/es/upload";
import type { UploadFile } from "antd/es/upload/interface";
import { useEffect, useState } from "react";
import FormBuilder, { type FormField } from "./form-builder";

interface TaskModalProps {
	open: boolean;
	title: string;
	initialValues?: any;
	onOk: (values: any) => void;
	onCancel: () => void;
}

const { TextArea } = Input;

const getBase64 = (file: RcFile): Promise<string> =>
	new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = () => resolve(reader.result as string);
		reader.onerror = (error) => reject(error);
	});

export default function TaskModal({
	open,
	title,
	initialValues,
	onOk,
	onCancel,
}: TaskModalProps) {
	const [form] = Form.useForm();
	const [fileList, setFileList] = useState<UploadFile[]>([]);
	const [taskFields, setTaskFields] = useState<FormField[]>([]);
	const [categories, setCategories] = useState<
		{ label: string; value: number }[]
	>([]);

	// 获取任务类别列表
	const fetchCategories = async () => {
		try {
			const res = await taskService.categoryList({ page: 1, limit: 100 });
			const options = res.items.map((item) => ({
				label: item.name,
				value: item.id,
			}));
			setCategories(options);
		} catch (error) {
			console.error("获取任务类别失败:", error);
		}
	};

	useEffect(() => {
		fetchCategories();
	}, []);

	useEffect(() => {
		if (initialValues) {
			form.setFieldsValue(initialValues);
			setFileList(initialValues.attachments || []);
			setTaskFields(initialValues.taskFields || []);
		} else {
			form.resetFields();
			setFileList([]);
			setTaskFields([]);
		}
	}, [initialValues, form]);

	const handleOk = async () => {
		try {
			const values = await form.validateFields();
			const taskFieldsData = taskFields.map((field, index) => ({
				...field,
				taskId: initialValues?.id || 0,
				sort: index,
				createTime: field.createTime || new Date(),
				updateTime: new Date(),
			}));

			if (initialValues) {
				// Handle edit case
				onOk({
					...values,
					taskFields: taskFieldsData,
				});
			} else {
				// Create new task
				const taskData = {
					...values,
					taskFields: taskFieldsData,
				};
				await taskService.taskAdd(taskData);
				message.success("任务创建成功");
				onOk(taskData);
			}
		} catch (error) {
			console.error("操作失败:", error);
			message.error("操作失败");
		}
	};

	const uploadProps: UploadProps = {
		onRemove: (file) => {
			const index = fileList.indexOf(file);
			const newFileList = fileList.slice();
			newFileList.splice(index, 1);
			setFileList(newFileList);
		},
		beforeUpload: async (file) => {
			const base64 = await getBase64(file);
			setFileList([
				...fileList,
				{
					uid: file.uid,
					name: file.name,
					status: "done",
					url: base64,
				},
			]);
			return false;
		},
		fileList,
	};

	const items = [
		{
			key: "basic",
			label: "基本信息",
			children: (
				<Form
					form={form}
					layout="vertical"
					initialValues={{
						status: "pending",
						priority: "medium",
						collectContent: {
							text: false,
							image: false,
						},
					}}
				>
					<Form.Item
						name="title"
						label="任务标题"
						rules={[{ required: true, message: "请输入任务标题" }]}
					>
						<Input placeholder="请输入任务标题" />
					</Form.Item>

					<Form.Item
						name="category_id"
						label="任务类别"
						rules={[{ required: true, message: "请选择任务类别" }]}
					>
						<Select
							placeholder="请选择任务类别"
							options={categories}
							loading={categories.length === 0}
						/>
					</Form.Item>

					<Form.Item
						name="price"
						label="单价(元)"
						rules={[{ required: true, message: "请输入任务单价" }]}
					>
						<InputNumber
							min={0}
							precision={2}
							placeholder="请输入任务单价"
							style={{ width: "100%" }}
						/>
					</Form.Item>

					<Form.Item
						name="reviewer"
						label="审核员"
						rules={[{ required: true, message: "请选择审核员" }]}
					>
						<Select
							placeholder="请选择审核员"
							options={[
								{ label: "张三", value: "张三" },
								{ label: "李四", value: "李四" },
								{ label: "王五", value: "王五" },
							]}
						/>
					</Form.Item>

					<Form.Item
						name="status"
						label="状态"
						rules={[{ required: true, message: "请选择任务状态" }]}
					>
						<Select
							placeholder="请选择任务状态"
							options={[
								{ label: "待发布", value: 0 },
								{ label: "进行中", value: 1 },
							]}
						/>
					</Form.Item>
				</Form>
			),
		},
		{
			key: "form",
			label: "表单配置",
			children: <FormBuilder value={taskFields} onChange={setTaskFields} />,
		},
	];

	return (
		<Modal
			open={open}
			title={title}
			width={1200}
			style={{ top: 20 }}
			bodyStyle={{ maxHeight: "calc(100vh - 200px)", overflowY: "auto" }}
			onOk={handleOk}
			onCancel={onCancel}
			destroyOnClose
		>
			<Tabs items={items} />
		</Modal>
	);
}
